package dbutil

import (
	"fmt"

	"gorm.io/gorm"
)

const (
	DefaultSize = 20
	MaxPageSize = 1000
)

func List(query *gorm.DB, v interface{}, page, size int, order ...interface{}) (int64, error) {
	if page < 1 {
		page = 1
	}
	if size < 1 {
		size = DefaultSize
	}
	if size > MaxPageSize {
		size = MaxPageSize
	}
	var total int64
	if err := query.Count(&total).Error; err != nil {
		return total, err
	}
	if len(order) > 0 {
		query = query.Order(order[0])
	}
	err := query.Offset(size * (page - 1)).Limit(size).Find(v).Error
	return total, err
}

func IfString(where *gorm.DB, column string, val string) *gorm.DB {
	if val != "" {
		return where.Where(fmt.Sprintf("%s = ?", column), val)
	}
	return where
}

func IfInt(where *gorm.DB, column string, val int) *gorm.DB {
	if val != 0 {
		return where.Where(fmt.Sprintf("%s = ?", column), val)
	}
	return where
}

//func TimeRange(query *gorm.DB, field string, timeRange []string) *gorm.DB {
//	if len(timeRange) != 2 {
//		return query
//	}
//	if timeRange[0] != "" {
//		t, _ := timeutil.Parse(timeRange[0])
//		query = query.Where(fmt.Sprintf("%s >= ?", field), t)
//	}
//	if timeRange[1] != "" {
//		t, _ := timeutil.Parse(timeRange[1])
//		query = query.Where(fmt.Sprintf("%s < ?", field), t)
//	}
//	return query
//}
